﻿using System.Collections.Generic;
using System.Linq;
using Gumini.JulaDB.Data;
using Gumini.JulaDB.Expressions;
using Gumini.JulaDB.Interfaces;

namespace Gumini.JulaDB.Planner
{
    /// <summary>
    /// Represent an item in the SELECT statement.
    /// </summary>
    internal class ColumnExpressionItem
    {
        public ColumnExpressionItem(Expression expression, string alias)
        {
            this.Expression = expression;
            this.Alias = alias;
        }

        /// <summary>
        /// Column alias is SELECT. Null if not specified.
        /// </summary>
        public string Alias { get; private set; }

        /// <summary>
        /// E.g. The '1/3+4' or 'name' part of 'SELECT 1/3+4, name from person'
        /// </summary>
        public Expression Expression { get; private set; }
        
        public object Evaluate(List<Row> rows, IHeading<IColumn> heading)
        {
            var contexts = rows.Select(r => r.GetEvaluationContext(heading)).ToList();
            var result = Expression.Evaluate(contexts);
            return result.Value;
        }
    }
}
